package ybt.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ybt.custom.AjaxResult;
import ybt.custom.BaseController;
import ybt.entity.Student;
import ybt.entity.TbClass;
import ybt.service.StudentService;
import ybt.service.TbClassService;
import ybt.web.form.StudentForm;
@Controller
@RequestMapping(value = "/student")
public class StudentController extends BaseController<Student, Integer, StudentForm>{

	@Autowired
	private StudentService service;
	@Autowired
	private TbClassService classService;
	@Value("${web.file_url}")
	private String  path;
	
	@Override
	public Specification<Student> buildSpec(StudentForm form) {
		@SuppressWarnings("serial")
		Specification<Student> spec=new Specification<Student>() {

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String stuNo = form.getStuNo();
				if(StringUtils.hasText(stuNo)) {
					rules.add(cb.like(root.get("stuNo"), "%"+stuNo+"%"));
				}
				Integer classId = form.getClassId();
				if(classId!=null) {
					rules.add(cb.equal(root.get("tbClass").get("id"), classId));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	
	@Override
	public void manage(ModelMap modelMap) {
		List<TbClass> list = classService.findAll();
		modelMap.put("bjs", list);
	}
	
	
	@Override
	public void edit(StudentForm form, ModelMap modelMap) throws InstantiationException, IllegalAccessException {
		Student model=new Student();
		Integer id = form.getId();
		if(id!=null) {
			model=service.findById(id);
		}else {
			model.setTbClass(new TbClass(form.getClassId()));
		}
		modelMap.put("model", model);
	}

	@Override
	public Object save(StudentForm form) {
		AjaxResult result = service.upload(form);
		return result;
	}
	
	@RequestMapping(value = "/download")
	@ResponseBody
	public void download(StudentForm form,HttpServletRequest request,HttpServletResponse response) {
		Integer id = form.getId();
		Student student = service.findById(id);
		String filename = student.getFilename();
		String uuid = student.getUuid();
		filename=getStr(request, filename);
		FileInputStream fis;
		try {
			fis = new FileInputStream(new File(path, uuid));
			response.setContentType("application/x-msdownload");
			response.addHeader("Access-Control-Allow-Origin", "*");
			response.addHeader("Content-Disposition", "attachment; filename=" + filename);
			ServletOutputStream out = response.getOutputStream();
			byte[] buf=new byte[2048];
			int n=0;
			while((n=fis.read(buf))!=-1) {
				out.write(buf, 0, n);
			}
			fis.close();
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/****
	 * 处理火狐下载乱码问题
	 * 
	 * @param request
	 * @param fileName
	 * @return
	 */
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
		// 仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表
		// *=utf-8'zh_cn'文件名.xx部分）
		String agent = request.getHeader("USER-AGENT");
		try {
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				// downloadFileName = "=?UTF-8?B?" + (new
				// String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
				// 设置字符集
				downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
			} else {
				downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadFileName;
	}
	
	@RequestMapping(value = "/resetPwd")
	@ResponseBody
	public Object resetPwd(Integer id) {
		Student model = service.findById(id);
		model.setPassword(new BCryptPasswordEncoder().encode("1111"));
		service.save(model);
		return new AjaxResult("密码重置成功");
	}

}
